var express = require('express');
var icon_router = express.Router();
var db = require('../../models')
const sequelize = require('sequelize');
const Op = sequelize.Op;
var comm = require('../../comm')



icon_router.post('/updateIcon', async (req, res) => {
    let status = await db.icons.updateIcon(req.body)
    res.json(status)
}),


    /**
   * @author: Shihh
   * @description: 删除单个图片单个标签
   * @param {type} 
   * @return: 
   */
    icon_router.post('/deleteTag', async (req, res) => {
        var id = req.body.id;
        var tag_id = req.body.tag_id;
        let result = await db.sequelize.transaction(t => {
            return db.tagIcon.destroy(
                {
                    where: {
                        "icon_id": id,
                        "tag_id": tag_id
                    },
                    transaction: t
                }).then(() => {
                    return db.tagIcon.findOne({
                        attributes: [
                            ['icon_id', 'id'],
                            [sequelize.fn('group_concat', sequelize.col('tag_id')), 'tagIds']
                        ],
                        raw: true,
                        where: {
                            'icon_id': id
                        },
                        transaction: t
                    }).then(icon => {
                        return db.icons.update(
                            { tagIds: icon.tagIds },
                            {
                                where: {
                                    "id": id
                                },
                                transaction: t
                            }
                        ).then(() => {
                            return true
                        }).catch(err => {
                            console.log(err)
                        })
                    })
                }).catch(err => {
                    console.log(err)
                })
        }).then(res => {
            return true
        }).catch(err => {
            console.log(err)
        })
        res.json(result)
    })


/**
 * @author: xgq
 * @description: 单个图片下架
 * @param {type} 
 * @return: 
 */
icon_router.get('/singleOff', async (req, res) => {
    var pars = {
        is_enable: 1,
        id: req.query.id
    }
    let result = await db.icons.update_is_enable(pars)
    res.json(result)
})

/**
* @author: xgq
* @description:单个图片上架 
* @param {type} 
* @return: 
*/
icon_router.get('/singleUp', async (req, res) => {
    var pars = {
        is_enable: 0,
        id: req.query.id
    }
    let result = await db.icons.update_is_enable(pars)
    res.json(result)
})


icon_router.post('/iconsDown', async (req, res) => {
    var ids = req.body.ids;
    var status = 1
    var pars = {
        ids,
        status
    }
    let result = await db.icons.iconsUpORDown(pars)
    res.json(result)
})

icon_router.post('/iconsUp', async (req, res) => {
    var ids = req.body.ids;
    var status = 0
    var pars = {
        ids,
        status
    }
    let result = await db.icons.iconsUpORDown(pars)
    res.json(result)
})



/**
 * @author: xgq
 * @description: 图标分组查询
 * @param {type} 
 * @return: 
 */
icon_router.post('/getIconListAndCount', async (req, res) => {
    var searchData = req.body.searchData
    var pageSet = req.body.pageSet
    var [page = 1, pagesize = 12] = [pageSet.page, pageSet.pagesize]
    let whereData = {}
    if (searchData.category) {
        whereData['category'] = searchData.category
    }

    if (searchData.status != null && searchData.status !== '') {

        whereData['is_enable'] = searchData.status
    }
    if (searchData.id) {
        whereData['id'] = {
            [Op.eq]: searchData.id
        }
    }
    if (searchData.designer) {
        whereData['designer'] = {
            [Op.like]: `%${searchData.designer}%`
        }
    }
    if (searchData.name) {
        whereData['name'] = {
            [Op.like]: `%${searchData.name}%`
        }
    }
    if (searchData.tagId) {
        let result = await db.tagIcon.findOne(
            {
                attributes: [[sequelize.fn('group_concat', sequelize.col('icon_id')), 'ids']],
                where: { 'tag_id': searchData.tagId },
                raw: true
            })
        if (result.ids) {
            var idArr = result.ids.split(',')
            if (searchData.id) {
                whereData['id'] = {
                    [Op.and]: {
                        [Op.in]: idArr,
                        [Op.like]: `%${searchData.id}%`
                    }
                }
            } else {
                whereData['id'] = {
                    [Op.in]: idArr
                }
            }
        }
    }
    let iconList = await db.icons.findAndCountAll({
        where: whereData,
        raw: true,
        attributes: ['*'],
        offset: pagesize * (page - 1),
        limit: parseInt(pagesize),
    })
    for (let r of iconList.rows) {
        if (r.tagIds) {
            let tagArr = r.tagIds.split(',')
            let labelArr = []
            for (let item of tagArr) {
                await new Promise(resolve => {
                    comm.redis.get(item, function (err, data) {
                        labelArr.push({
                            id: item,
                            name: data
                        });
                        resolve()
                    })
                })
            }
            r['label'] = labelArr
        }
        // var categoryArr = []
        // await new Promise(resolve => {
        //     comm.redis.hget('category', r.category, async function (err, data) {
        //         let result = JSON.parse(data)
        //         if (result.parentid !== 0) {
        //             await comm.redis.hget('category', result.parentid, function (err, data) {
        //                 let p_result = JSON.parse(data)
        //                 categoryArr.push(p_result.name)
        //                 categoryArr.push(result.name)
        //                 r.category = categoryArr.toString()
        //             })
        //         } else {
        //             categoryArr.push(result.name)
        //             r.category = categoryArr.toString()
        //         }
        //         resolve()
        //     })
        // })
    }
    res.json(iconList)
})

module.exports = icon_router